﻿using System;
using System.IO;
using System.Text;

namespace Common
{
    /// <summary>
    /// 写数据类
    /// </summary>
    public class DataWriter
    {
        /// <summary>
        /// 将GPS原始数据写入指定日志文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="receivedBuffer">收到的byte数据</param>
        public static void WriteGpsBinaryData(string filePath, byte[] receivedBuffer)
        {
            try
            {
                Directory.CreateDirectory(filePath.Substring(0, filePath.LastIndexOf("\\")));
                FileStream fileStream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.Write);

                BinaryWriter binaryWriter = new BinaryWriter(fileStream);

                binaryWriter.BaseStream.Seek(0, SeekOrigin.End);
                binaryWriter.Write(receivedBuffer);
                binaryWriter.Write("\t\n");
                binaryWriter.Flush();
                binaryWriter.Close();
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, null);
            }
        }

        /// <summary>
        /// 写入 gps 文本数据
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="strReceiveTime"></param>
        /// <param name="receivedBuffer"></param>
        public static void WriteGpsTextData(string filePath, string strReceiveTime, ReadOnlySpan<byte> receivedBuffer)
        {
            try
            {
                StringBuilder sbBinaryData = new StringBuilder();
                for (int i = 0; i < receivedBuffer.Length; i++)
                {
                    sbBinaryData.Append(receivedBuffer[i].ToString("X2"));
                    if (i < receivedBuffer.Length - 1)
                        sbBinaryData.Append(",");
                }

                Directory.CreateDirectory(filePath.Substring(0, filePath.LastIndexOf("\\")));
                using (FileStream fileStream = File.Open(filePath, FileMode.Append, FileAccess.Write))
                {
                    StreamWriter txtWriter = new StreamWriter(fileStream);
                    txtWriter.WriteLine(strReceiveTime + "---" + sbBinaryData.ToString());
                    txtWriter.Close();
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, null);
            }
        }
    }
}